package sys.news.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 字符乱码过滤器
 */
//如果只有一个值 用value=""
@WebFilter(value="*.do",initParams = {
        @WebInitParam(name="charset" ,value="UTF-8"),
        @WebInitParam(name="charset2", value="GBK")
})//过滤所有后台请求*.do  不加斜杠
public class CharsetFilter implements Filter {
    private String charset;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        charset = filterConfig.getInitParameter("charset");
        System.out.println("字符编码过滤器启动。。。。"+charset);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("字符编码过滤器UTF-8。。。");
        HttpServletRequest request = (HttpServletRequest)servletRequest;//转换子类型
        request.setCharacterEncoding("UTF-8");//设置请求编码
        HttpServletResponse response = (HttpServletResponse)servletResponse;//转型子类型
        response.setCharacterEncoding("UTF-8");//设置响应编码
        filterChain.doFilter(request,response);//放行 进入一下后台资源
    }

    @Override
    public void destroy() {

    }
}
